﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetCasClient.Security;
using DotNetCasClient.Utils;
using System.Web.Security;

namespace MvcDemo.Controllers
{
    public class UserInfoController : Controller
    {
        //
        // GET: /UserInfo/
        [Authorize]
        public ActionResult Index()
        {
            string userName = User.Identity.Name;

            CasPrincipal p = System.Web.HttpContext.Current.User as CasPrincipal;

            //获得所有传递过来的用户属性
            Dictionary<string, string> userAttrs = new Dictionary<string, string>();
            var cnValue = UserAttrHelper.GetUserAttrValueByParamName("cn");
            var aliasValue = UserAttrHelper.GetUserAttrValueByParamName("alias");
            userAttrs.Add("cn", string.Join(",", cnValue));
            userAttrs.Add("alias", string.Join(",", aliasValue));
            ViewData["user"] = userName.ToString();
            ViewData["userAttrs"] = userAttrs;
            return View();
        }

        public static FormsAuthenticationTicket GetFormsAuthenticationTicket()
        {
            //Initialize();
            HttpContext context = System.Web.HttpContext.Current;
            HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie == null)
            {
                return null;
            }

            if (cookie.Expires != DateTime.MinValue && cookie.Expires < DateTime.Now)
            {
                // ClearAuthCookie();
                return null;
            }

            if (String.IsNullOrEmpty(cookie.Value))
            {
                //ClearAuthCookie();
                return null;
            }

            FormsAuthenticationTicket formsAuthTicket;
            try
            {
                formsAuthTicket = FormsAuthentication.Decrypt(cookie.Value);
            }
            catch
            {
                //ClearAuthCookie();
                return null;
            }

            if (formsAuthTicket == null)
            {
                //ClearAuthCookie();
                return null;
            }

            if (formsAuthTicket.Expired)
            {
                //ClearAuthCookie();
                return null;
            }

            if (String.IsNullOrEmpty(formsAuthTicket.UserData))
            {
                //ClearAuthCookie();
                return null;
            }

            return formsAuthTicket;
        }

    }
}
